Longest Palindromic Subsequence
LeetCode 516 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given a string s, find the longest palindromic subsequence's length in s.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".
Constraints:
- `1 <= s.length <= 1000`
- `s` consists only of lowercase English letters.
Topics: String, Dynamic Programming
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 120 ms)β
| Metric | Value |
|---|---|
| Runtime | 120 ms |
| Memory | 39.9 MB |
| Date | 2021-12-20 |
public class Solution {
public int LongestPalindromeSubseq(string s) {
int n = s.Length;
int[,] dp = new int[n+1, n+1];
for(int i=0;i<n;i++)
{
for (int j = 0; j < n; j++)
{
dp[i+1,j+1] = (s[i] == s[n-1-j]) ? dp[i,j]+1 : Math.Max(dp[i,j+1], dp[i+1,j]);
}
}
return dp[n,n];
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| DP (2D) | $O(n Γ m)$ | $O(n Γ m)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.